<template>
  <div>
    <el-tree :data="jsonTree" show-checkbox node-key="id" ref="tree" />
    <div
      :style="{
            position: 'absolute',
            left: 0,
            bottom: 0,
            right: 0,
            zIndex: 9,
            borderTop: '1px solid #e9e9e9',
            padding: '10px 20px',
            background: '#fff',
            textAlign: 'right'
          }"
    >
      <el-button @click="candel()">取 消</el-button>
      <el-button type="primary" @click="savetree()">保 存</el-button>
    </div>
  </div>
</template>
<script>
export default {
  name: 'zjstorefrontDeptadd',
  data() {
    return {
      tree: this.getdata.list
    };
  },
  props: ['getdata'],
  created() {},
  computed: {
    jsonTree() {
      console.log(this.getdata);
      let arr = JSON.parse(JSON.stringify(this.getdata.list));
      console.log(arr, arr.forEach);
      arr.forEach(el => (el.label = el.text));
      arr.forEach(el => (el.parentId = el.parent));
      console.log(arr, 'arr');
      let array = this.getJsonTree(arr, 'id', 'parentId');
      return array;
    }
  },
  methods: {
    getJsonTree(data, id, parentId) {
      console.log(data, 'data');
      data.forEach(function(item) {
        delete item.children;
      });
      const map = {};
      data.forEach(function(item) {
        map[item[id]] = item;
      });

      const val = [];
      data.forEach(function(item) {
        const parent = map[item[parentId]];

        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          val.push(item);
        }
      });

      return val;
    },
    savetree() {
      console.log(this.getdata);
      let json = JSON.parse(JSON.stringify(this.getdata));
      json.list = this.$refs.tree.getCheckedNodes(true);
      console.log(this.$refs.tree.getCheckedNodes(true));
      this.$emit('change', json);
    },
    candel() {
      this.$emit('closeadd', false);
    }
  }
};
</script>

